<template>
  <div>
    <div class="header-tool">
      <a-input-search
        style="width: 300px; margin-right: 10px"
        v-model:value="searchValue"
        placeholder="请输入标题搜索"
        @search="onSearch"
      />
      <a-button
        style="margin-right: 20px"
        class="mr10"
        type="primary"
        enter-button
        @click="onSearch()"
      >
        搜索
      </a-button>

      <a-button
        type="primary"
        @click="handleEdit()"
      >
        新增
      </a-button>
      <a-button
        :type="mapRows.length == 0 ? 'dashed' : 'primary'"
        @click="batchLoading(1)"
      >
        批量上架
      </a-button>
      <a-button
        :type="mapRows.length == 0 ? 'dashed' : 'primary'"
        @click="batchLoading(0)"
      >
        批量下架
      </a-button>

      <a-button
        class="mr10"
        type="primary"
        @click="reLoad()"
      >
        刷新
      </a-button>
      <a-button
      v-if="getPower(32)"
        class="mr10"
        type="primary"
        :loading="loadingSync"
        @click="articleSync()"
      >
        文章同步
      </a-button>
    </div>

    <a-table
      :row-key="(record) => record.news_id"
      :rowSelection="{
        onChange: onSelectChange,

        selectedRowKeys: mapRows
      }"
      :columns="newColumns"
      :dataSource="activities"
      :pagination="
        isObject(pagination)
          ? {
              showQuickJumper: true,
              total: pagination.total,
              current: pagination.current,
              pageSize: pagination.pageSize,
              showTotal: (total) => `共计 ${pagination.total} 条`
            }
          : false
      "
      @change="handleTableChange"
    >
      <template #bodyCell="{ column, record }">
        <template v-if="column.dataIndex === 'image'">
          <img
            style="width: 50px; height: 50px"
            :src="record.image"
          />
        </template>
        <template v-if="column.dataIndex === 'status'">
          <a-switch
            @change="changeDel($event, record)"
            checked-children="上架"
            un-checked-children="下架"
            v-model:checked="record.status"
          />
        </template>

        <template v-if="column.dataIndex === 'action'">
          <span>
            <a
              v-if="!record.url"
              @click="handleEdit(record)"
            >
              编辑
            </a>
            <a-divider type="vertical" />
            <a-popconfirm
              class="gap-popconfirm"
              title="确定删除吗？"
              ok-text="确认"
              cancel-text="取消"
              @confirm="handleDelete(record)"
            >
              <a>删除</a>
            </a-popconfirm>
          </span>
        </template>
      </template>
    </a-table>

    <newsForm
      ref="newsFormEle"
      @success="reload"
    />
  </div>
</template>

<script setup>
import { getPower } from '@/utils/power'
  import { isObject } from 'lodash-es'
  import { message } from 'ant-design-vue'
  import axios from 'axios'
  import { ref, onMounted, reactive, computed } from 'vue'
  import { useRouter } from 'vue-router'
  import { ElButton, ElTable, ElTableColumn, ElDialog } from 'element-plus'
  import newsForm from './newsForm.vue'
  import { newsList, newsDel, newsIsDestroy, newsSync } from '@/api/index'
  const pagination = reactive({
    current: 1,
    pageSize: 10,
    total: 0
  })
  const activities = ref([])
  const newColumns = [
    // {
    //   title: 'id',
    //   dataIndex: 'news_id',
    //   key: 'ID'
    // },
    {
      title: '标题',
      dataIndex: 'title',

      ellipsis: true
    },
    {
      title: '主图',
      dataIndex: 'image',
      width: '100px'
    },
    {
      title: '收藏',
      dataIndex: 'fav_num',
      width: '80px'
    },
    {
      title: '上架',
      dataIndex: 'status',
      width: '80px'
    },
    {
      title: '创建时间',
      dataIndex: 'created_at',
      width: '120px'
    },
    {
      title: '操作',
      dataIndex: 'action',
      width: '200px',
      fixed: 'right'
    }
  ]
const loadingSync=ref(false)
  const mapRows = ref([])
  const articleSync = async () => {
    try{
      loadingSync.value=true
      await newsSync()
      message.success('同步成功')
      reLoad()
    }finally{
      loadingSync.value=false
    }
    // await newsSync()
    // message.success('同步成功')
    // reLoad()
  }
  const onSelectChange = (selectedRowKeys, selectedRows) => {
    mapRows.value = selectedRowKeys
  }

  const batchLoading = (status) => {
    if (mapRows.value.length == 0) {
      message.error('请选择要操作的项')
      return
    }
    console.log(mapRows.value)

    newsIsDestroy({ news_id: mapRows.value, is_destroy: status == 1 ? true : false })
      .then((res) => {
        if (res.errorCode) {
          message.error(res.msg || '操作失败')
          return
        }
        message.success('操作成功！')
        getList()
      })
      .catch((err) => {
        message.error(err.msg)
      })
  }
  const newsFormEle = ref()

  const searchValue = ref('')
  const onSearch = () => {
    pagination.current = 1
    getList()
  }
  const getList = () => {
    newsList({
      page: pagination.current,
      title: searchValue.value,
      pageSize: pagination.pageSize
    })
      .then((res) => {
        if (res.errorCode) {
          message.error(res.msg || '操作失败')
          return
        }
        activities.value = res.data.map((val) => {
          return {
            ...val,
            status: val.is_del == 1 ? true : false
          }
        })
        // activities.value = res.data
        pagination.total = res.total
      })
      .catch((err) => {
        message.error(err.msg)
      })
  }
  getList()
  const handleTableChange = ({ current, pageSize }) => {
    pagination.current = current
    pagination.pageSize = pageSize
    getList()
  }
  // 编辑
  const handleEdit = (row) => {
    newsFormEle.value.init(row)
  }
  // 上下架
  const changeDel = (e, row) => {
    newsIsDestroy({ news_id: [row.news_id], is_destroy: e })
      .then((res) => {
        if (res.errorCode) {
          message.error(res.msg || '操作失败')
          return
        }
        message.success('操作成功！')
        getList() // Refresh activity list after deletion
      })
      .catch((err) => {
        message.error(err.msg)
        row.is_del = !e
      })
  }
  const handleDelete = (row) => {
    newsDel({ news_id: row.news_id })
      .then((res) => {
        if (res.errorCode) {
          message.error(res.msg || '操作失败')
          return
        }
        message.success('操作成功！')
        getList() // Refresh activity list after deletion
      })
      .catch((err) => {
        message.error(err.msg)
      })
  }
  const reLoad = () => {
    pagination.current = 1
    getList()
  }

  const reload = () => {
    getList()
  }
</script>

<style scoped>
  .header-tool {
    display: flex;
    justify-content: flex-start;
    align-items: center;
    margin-bottom: 10px;
  }

  .header-tool button {
    margin-right: 5px;
  }
</style>
